﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using Newtonsoft.Json;
using ERP_SaaS_WinForm.生产计划_派单_车间.CarManage;
using ERP_SaaS_WinForm.生产计划_派单_车间.Site;
using ERP_SaaS_WinForm.生产计划_派单_车间.ProductLine;
using ERP_SaaS_WinForm.生产计划_派单_车间.apiResquest;

namespace ERP_SaaS_WinForm.生产计划_派单_车间
{
    public partial class CarManagement : Form
    {
        private List<CarData> carList = new List<CarData>();
        private CCWin.SkinControl.SkinDataGridView dgvCarInfo;
        
        // 站点管理相关
        private List<SiteData> siteList = new List<SiteData>();
        private CCWin.SkinControl.SkinDataGridView dgvSites;
        private CCWin.SkinControl.SkinButton btnSiteRefresh;
        private CCWin.SkinControl.SkinButton btnSiteAdd;
        private CCWin.SkinControl.SkinButton btnSiteBack;
        
        // 站点新增表单控件
        private CCWin.SkinControl.SkinTextBox txtSiteCode;
        private CCWin.SkinControl.SkinTextBox txtSiteName;
        private CCWin.SkinControl.SkinComboBox cboSiteType;
        private CCWin.SkinControl.SkinComboBox cboSiteCarId;
        private CCWin.SkinControl.SkinComboBox cboSiteLineId;
        private CCWin.SkinControl.SkinComboBox cboSiteProcessId;
        private CCWin.SkinControl.SkinComboBox cboSiteLocal;
        private CCWin.SkinControl.SkinButton btnSiteSave;
        private CCWin.SkinControl.SkinButton btnSiteClear;
        
        // 生产线管理相关
        private List<ProductLineData> productLineList = new List<ProductLineData>();
        private CCWin.SkinControl.SkinDataGridView dgvProductLines;
        private CCWin.SkinControl.SkinButton btnProductLineRefresh;
        private CCWin.SkinControl.SkinButton btnProductLineAdd;
        private CCWin.SkinControl.SkinButton btnProductLineBack;
        
        // 生产线新增表单控件
        private CCWin.SkinControl.SkinTextBox txtLineCode;
        private CCWin.SkinControl.SkinTextBox txtLineName;
        private CCWin.SkinControl.SkinComboBox cboLineType;
        private CCWin.SkinControl.SkinComboBox cboLineCarId;
        private CCWin.SkinControl.SkinButton btnLineSave;
        private CCWin.SkinControl.SkinButton btnLineClear;
        
        public CarManagement()
        {
            InitializeComponent();
            InitializeForm();
            InitializeSiteManagement();
            InitializeSiteAddPage();
            InitializeProductLineAddPage();
            InitializeProductLineManagement();
        }
        
        /// <summary>
        /// 初始化窗体
        /// </summary>
        private void InitializeForm()
        {
            try
            {
                // 设置窗体标题
                this.Text = "车间管理";
                
                // 绑定提交按钮事件
                if (btnCarAdd != null)
                {
                    btnCarAdd.Click += BtnCarAdd_Click;
                }
                
                // 绑定选择负责人按钮事件
                if (btnLeader != null)
                {
                    btnLeader.Click += BtnLeader_Click;
                }
                
                // 初始化车间信息页面
                InitializeCarInfoPage();
                
                // 加载车间数据
                LoadCarData();
                
                Console.WriteLine("车间管理窗体初始化完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化窗体时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 初始化车间信息页面
        /// </summary>
        private void InitializeCarInfoPage()
        {
            try
            {
                // 检查车间信息页面是否存在
                if (tabCarInfo == null)
                {
                    MessageBox.Show("车间信息页面未找到", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                
                // 创建车间信息DataGridView控件
                var dgvCarInfo = new CCWin.SkinControl.SkinDataGridView();
                dgvCarInfo.Name = "dgvCarInfo";
                dgvCarInfo.Dock = DockStyle.Fill;
                dgvCarInfo.Location = new Point(0, 0);
                dgvCarInfo.Size = new Size(tabCarInfo.Width, tabCarInfo.Height);
                
                // 设置DataGridView的基本属性
                dgvCarInfo.AutoGenerateColumns = false;
                dgvCarInfo.AllowUserToAddRows = false;
                dgvCarInfo.AllowUserToDeleteRows = false;
                dgvCarInfo.ReadOnly = true;
                dgvCarInfo.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                dgvCarInfo.MultiSelect = false;
                dgvCarInfo.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                
                // 添加列定义
                // 车间编号列
                DataGridViewTextBoxColumn colCarCode = new DataGridViewTextBoxColumn();
                colCarCode.HeaderText = "车间编号";
                colCarCode.DataPropertyName = "CarCode";
                colCarCode.Width = 90;
                dgvCarInfo.Columns.Add(colCarCode);
                
                // 车间名称列
                DataGridViewTextBoxColumn colCarName = new DataGridViewTextBoxColumn();
                colCarName.HeaderText = "车间名称";
                colCarName.DataPropertyName = "CarName";
                colCarName.Width = 100;
                dgvCarInfo.Columns.Add(colCarName);
                
                // 车间面积列
                DataGridViewTextBoxColumn colCarArea = new DataGridViewTextBoxColumn();
                colCarArea.HeaderText = "车间面积";
                colCarArea.DataPropertyName = "CarArea";
                colCarArea.Width = 100;
                dgvCarInfo.Columns.Add(colCarArea);
                
                // 负责人列
                DataGridViewTextBoxColumn colLeader = new DataGridViewTextBoxColumn();
                colLeader.HeaderText = "负责人";
                colLeader.DataPropertyName = "Leader";
                colLeader.Width = 100;
                dgvCarInfo.Columns.Add(colLeader);
                
                // 设置CSkin DataGridView样式
                dgvCarInfo.BackgroundColor = Color.White;
                dgvCarInfo.BorderStyle = BorderStyle.None;
                dgvCarInfo.GridColor = Color.LightGray;
                dgvCarInfo.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(240, 240, 240);
                dgvCarInfo.ColumnHeadersDefaultCellStyle.Font = new Font("微软雅黑", 9F, FontStyle.Bold);
                dgvCarInfo.DefaultCellStyle.Font = new Font("微软雅黑", 9F);
                dgvCarInfo.RowHeadersVisible = false;
                
                // 将DataGridView添加到车间信息页面
                tabCarInfo.Controls.Add(dgvCarInfo);
                
                // 保存控件引用
                this.dgvCarInfo = dgvCarInfo;
                
                Console.WriteLine("车间信息页面初始化完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"初始化车间信息页面时出错: {ex.Message}");
                MessageBox.Show($"初始化车间信息页面时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 加载车间数据
        /// </summary>
        private async void LoadCarData()
        {
            try
            {
                Console.WriteLine("=== 开始加载车间数据 ===");
                
                // 检查dgvCarInfo控件是否存在
                if (dgvCarInfo == null)
                {
                    MessageBox.Show("车间信息 DataGridView控件未找到", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                
                // 显示加载状态
                dgvCarInfo.DataSource = null;
                
                // 调用车间信息 API
                Console.WriteLine("正在调用车间信息API...");
                var apiResponse = await ApiRequestHelper.GetAsync<ApiCarInfoResponse>("api/Car/GetCar");
                
                if (apiResponse.Success && apiResponse.Data != null && apiResponse.Data.code == 200)
                {
                    var response = apiResponse.Data;
                    Console.WriteLine($"车间信息API调用成功，数据条数: {response.data.Count}");
                    
                    // 设置车间数据到DataGridView
                    carList = response.data;
                    dgvCarInfo.DataSource = carList;
                    
                    // 调整列宽
                    dgvCarInfo.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
                    
                    Console.WriteLine($"成功加载 {carList.Count} 个车间数据");
                    Console.WriteLine("=== 车间数据加载完成 ===");
                    
                    // 车间数据加载完成后，加载站点和生产线数据
                    LoadSiteData();
                    LoadProductLineData();
                }
                else
                {
                    string errorMsg = apiResponse.Success ? 
                        $"车间数据加载失败: {apiResponse.Data?.msg ?? "未知错误"}" : 
                        $"请求失败: {apiResponse.Message}";
                    Console.WriteLine($"车间信息API调用失败: {errorMsg}");
                    ApiRequestHelper.ShowError(errorMsg);
                }
            }
            catch (HttpRequestException ex)
            {
                Console.WriteLine($"HTTP请求错误: {ex.Message}");
                MessageBox.Show($"网络请求失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (JsonException ex)
            {
                Console.WriteLine($"JSON解析错误: {ex.Message}");
                MessageBox.Show($"数据解析失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载车间数据时出错: {ex.Message}");
                MessageBox.Show($"加载车间数据时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 提交按钮点击事件
        /// </summary>
        private async void BtnCarAdd_Click(object sender, EventArgs e)
        {
            try
            {
                Console.WriteLine("=== 开始提交车间信息 ===");
                
                // 验证输入数据
                if (!ValidateInput())
                {
                    return;
                }
                
                // 构建车间数据
                var carData = BuildCarData();
                
                // 调用API添加车间
                bool success = await AddCarAsync(carData);
                
                if (success)
                {
                    MessageBox.Show("车间信息添加成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ClearForm();
                    
                    // 刷新车间信息列表
                    LoadCarData();
                }
                
                Console.WriteLine("=== 提交车间信息完成 ===");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"提交车间信息时出错: {ex.Message}");
                MessageBox.Show($"提交车间信息时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 选择负责人按钮点击事件
        /// </summary>
        private void BtnLeader_Click(object sender, EventArgs e)
        {
            try
            {
                // 打开选择用户窗体
                using (var selectUsersForm = new SelectUsers())
                {
                    if (selectUsersForm.ShowDialog() == DialogResult.OK)
                    {
                        // 获取选中的用户信息
                        var selectedUser = selectUsersForm.SelectedUser;
                        if (selectedUser != null)
                        {
                            txtCarLeader.Text = selectedUser.userName;
                            Console.WriteLine($"已选择负责人: {selectedUser.userName} (部门: {selectedUser.departmentName})");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"选择负责人时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 验证输入数据
        /// </summary>
        private bool ValidateInput()
        {
            // 验证车间编号
            if (string.IsNullOrWhiteSpace(txtCarCode.Text))
            {
                MessageBox.Show("请输入车间编号", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtCarCode.Focus();
                return false;
            }
            
            // 验证车间名称
            if (string.IsNullOrWhiteSpace(txtCarName.Text))
            {
                MessageBox.Show("请输入车间名称", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtCarName.Focus();
                return false;
            }
            
            // 验证车间面积
            if (string.IsNullOrWhiteSpace(txtCarArea.Text))
            {
                MessageBox.Show("请输入车间面积", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtCarArea.Focus();
                return false;
            }
            
            // 验证负责人
            if (string.IsNullOrWhiteSpace(txtCarLeader.Text))
            {
                MessageBox.Show("请选择负责人", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtCarLeader.Focus();
                return false;
            }
            
            return true;
        }
        
        /// <summary>
        /// 构建车间数据
        /// </summary>
        private CarData BuildCarData()
        {
            return new CarData
            {
                CarCode = txtCarCode.Text.Trim(),
                CarName = txtCarName.Text.Trim(),
                CarArea = txtCarArea.Text.Trim(),
                Leader = txtCarLeader.Text.Trim()
            };
        }
        
        /// <summary>
        /// 调用API添加车间
        /// </summary>
        private async Task<bool> AddCarAsync(CarData carData)
        {
            try
            {
                Console.WriteLine("正在调用添加车间API...");
                
                // 构建请求数据
                var requestData = new
                {
                    carCode = carData.CarCode,
                    carName = carData.CarName,
                    carArea = carData.CarArea,
                    leader = carData.Leader
                };
                
                Console.WriteLine($"请求数据: {JsonConvert.SerializeObject(requestData)}");
                
                // 发送POST请求
                var apiResponse = await ApiRequestHelper.PostAsync<ApiCarResponse>("api/Car/AddCar", requestData);
                
                if (apiResponse.Success && apiResponse.Data != null && apiResponse.Data.code == 200)
                {
                    Console.WriteLine($"车间添加成功，影响行数: {apiResponse.Data.data}");
                    return true;
                }
                else
                {
                    string errorMsg = apiResponse.Success ? 
                        $"车间添加失败: {apiResponse.Data?.msg ?? "未知错误"}" : 
                        $"请求失败: {apiResponse.Message}";
                    Console.WriteLine($"车间添加失败: {errorMsg}");
                    ApiRequestHelper.ShowError(errorMsg);
                    return false;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"添加车间时出错: {ex.Message}");
                ApiRequestHelper.ShowError($"添加车间时出错: {ex.Message}");
                return false;
            }
        }
        
        /// <summary>
        /// 清空表单
        /// </summary>
        private void ClearForm()
        {
            try
            {
                txtCarCode.Text = "";
                txtCarName.Text = "";
                txtCarArea.Text = "";
                txtCarLeader.Text = "";
                
                // 将焦点设置到车间编号输入框
                txtCarCode.Focus();
                
                Console.WriteLine("表单已清空");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"清空表单时出错: {ex.Message}");
            }
        }

        private void tabCarInfo_Click(object sender, EventArgs e)
        {

        }

        #region 站点管理功能

        /// <summary>
        /// 初始化站点管理
        /// </summary>
        private void InitializeSiteManagement()
        {
            try
            {
                // 初始化站点管理页面
                InitializeSiteManagePage();
                
                Console.WriteLine("站点管理初始化完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化站点管理时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 初始化站点管理页面
        /// </summary>
        private void InitializeSiteManagePage()
        {
            try
            {
                if (tabSiteManage == null)
                {
                    MessageBox.Show("站点管理页面未找到", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 创建站点管理DataGridView
                dgvSites = new CCWin.SkinControl.SkinDataGridView();
                dgvSites.Name = "dgvSites";
                dgvSites.Dock = DockStyle.Fill;
                dgvSites.Location = new Point(0, 0);
                dgvSites.Size = new Size(tabSiteManage.Width, tabSiteManage.Height - 60);

                // 设置DataGridView属性
                dgvSites.AutoGenerateColumns = false;
                dgvSites.AllowUserToAddRows = false;
                dgvSites.AllowUserToDeleteRows = false;
                dgvSites.ReadOnly = true;
                dgvSites.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                dgvSites.MultiSelect = false;
                dgvSites.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

                // 添加列定义
                dgvSites.Columns.Add(new DataGridViewTextBoxColumn
                {
                    HeaderText = "站点编号",
                    DataPropertyName = "SiteCode",
                    Width = 100
                });

                dgvSites.Columns.Add(new DataGridViewTextBoxColumn
                {
                    HeaderText = "站点名称",
                    DataPropertyName = "SiteName",
                    Width = 120
                });

                // 添加站点类型列（自定义显示）
                var siteTypeColumn = new DataGridViewTextBoxColumn
                {
                    HeaderText = "站点类型",
                    Name = "SiteTypeColumn",
                    Width = 100
                };
                dgvSites.Columns.Add(siteTypeColumn);

                // 添加所属车间列（直接绑定CarName字段）
                dgvSites.Columns.Add(new DataGridViewTextBoxColumn
                {
                    HeaderText = "所属车间",
                    DataPropertyName = "CarName",
                    Width = 100
                });

                dgvSites.Columns.Add(new DataGridViewTextBoxColumn
                {
                    HeaderText = "所属生产线",
                    DataPropertyName = "LineName",
                    Width = 120
                });

                // 添加工序列（自定义显示）
                var processColumn = new DataGridViewTextBoxColumn
                {
                    HeaderText = "工序",
                    Name = "ProcessColumn",
                    Width = 80
                };
                dgvSites.Columns.Add(processColumn);

                dgvSites.Columns.Add(new DataGridViewTextBoxColumn
                {
                    HeaderText = "位置",
                    DataPropertyName = "SiteLocal",
                    Width = 100
                });

                // 设置样式
                dgvSites.BackgroundColor = Color.White;
                dgvSites.BorderStyle = BorderStyle.None;
                dgvSites.GridColor = Color.LightGray;
                dgvSites.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(240, 240, 240);
                dgvSites.ColumnHeadersDefaultCellStyle.Font = new Font("微软雅黑", 9F, FontStyle.Bold);
                dgvSites.DefaultCellStyle.Font = new Font("微软雅黑", 9F);
                dgvSites.RowHeadersVisible = false;
                
                // 绑定数据绑定完成事件
                dgvSites.DataBindingComplete += DgvSites_DataBindingComplete;

                // 创建按钮面板
                var buttonPanel = new Panel
                {
                    Dock = DockStyle.Bottom,
                    Height = 60,
                    BackColor = Color.White
                };

                // 创建按钮
                btnSiteRefresh = new CCWin.SkinControl.SkinButton
                {
                    Text = "刷新",
                    Size = new Size(80, 35),
                    Location = new Point(20, 15)
                };
                btnSiteRefresh.Click += BtnSiteRefresh_Click;

                btnSiteAdd = new CCWin.SkinControl.SkinButton
                {
                    Text = "新增站点",
                    Size = new Size(100, 35),
                    Location = new Point(120, 15)
                };
                btnSiteAdd.Click += BtnSiteAdd_Click;

                // 添加控件到面板
                buttonPanel.Controls.Add(btnSiteRefresh);
                buttonPanel.Controls.Add(btnSiteAdd);

                // 添加控件到页面
                tabSiteManage.Controls.Add(dgvSites);
                tabSiteManage.Controls.Add(buttonPanel);

                Console.WriteLine("站点管理页面初始化完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"初始化站点管理页面时出错: {ex.Message}");
                MessageBox.Show($"初始化站点管理页面时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 加载站点数据
        /// </summary>
        private async void LoadSiteData()
        {
            try
            {
                Console.WriteLine("=== 开始加载站点数据 ===");

                if (dgvSites == null)
                {
                    MessageBox.Show("站点DataGridView控件未找到", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                dgvSites.DataSource = null;

                Console.WriteLine("正在调用站点信息API...");
                var apiResponse = await ApiRequestHelper.GetAsync<ApiSiteResponse>("api/Car/GetSite");

                if (apiResponse.Success && apiResponse.Data?.code == 200 && apiResponse.Data.data != null)
                {
                    Console.WriteLine($"站点信息API调用成功，数据条数: {apiResponse.Data.data.Count}");

                    siteList = apiResponse.Data.data;
                    dgvSites.DataSource = siteList;

                    dgvSites.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);

                    Console.WriteLine($"成功加载 {siteList.Count} 个站点数据");
                    Console.WriteLine("=== 站点数据加载完成 ===");
                }
                else
                {
                    Console.WriteLine($"站点信息API调用失败: {apiResponse.Message}");
                    ApiRequestHelper.ShowError($"站点数据加载失败: {apiResponse.Message}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载站点数据时出错: {ex.Message}");
                MessageBox.Show($"加载站点数据时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 站点数据绑定完成事件
        /// </summary>
        private void DgvSites_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            try
            {
                // 手动填充站点类型和工序列
                for (int i = 0; i < dgvSites.Rows.Count; i++)
                {
                    if (i < siteList.Count)
                    {
                        var site = siteList[i];
                        var siteTypeText = GetSiteTypeText(site.SiteType);
                        var processText = GetProcessText(site.ProcessId);
                        
                        Console.WriteLine($"站点 {site.SiteCode}: SiteType={site.SiteType} -> {siteTypeText}, ProcessId={site.ProcessId} -> {processText}");
                        
                        dgvSites.Rows[i].Cells["SiteTypeColumn"].Value = siteTypeText;
                        dgvSites.Rows[i].Cells["ProcessColumn"].Value = processText;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"填充站点自定义列时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 站点刷新按钮点击事件
        /// </summary>
        private void BtnSiteRefresh_Click(object sender, EventArgs e)
        {
            LoadSiteData();
        }

        /// <summary>
        /// 站点新增按钮点击事件
        /// </summary>
        private void BtnSiteAdd_Click(object sender, EventArgs e)
        {
            ShowSiteAddForm();
        }

        /// <summary>
        /// 显示站点新增表单
        /// </summary>
        private void ShowSiteAddForm()
        {
            try
            {
                // 创建站点新增表单
                var siteAddForm = new Form
                {
                    Text = "新增站点",
                    Size = new Size(500, 400),
                    StartPosition = FormStartPosition.CenterParent,
                    FormBorderStyle = FormBorderStyle.FixedDialog,
                    MaximizeBox = false,
                    MinimizeBox = false
                };

                // 创建表单控件
                var lblSiteCode = new CCWin.SkinControl.SkinLabel { Text = "站点编号:", Location = new Point(30, 30) };
                txtSiteCode = new CCWin.SkinControl.SkinTextBox { Location = new Point(120, 30), Size = new Size(200, 25) };

                var lblSiteName = new CCWin.SkinControl.SkinLabel { Text = "站点名称:", Location = new Point(30, 70) };
                txtSiteName = new CCWin.SkinControl.SkinTextBox { Location = new Point(120, 70), Size = new Size(200, 25) };

                var lblSiteType = new CCWin.SkinControl.SkinLabel { Text = "站点类型:", Location = new Point(30, 110) };
                cboSiteType = new CCWin.SkinControl.SkinComboBox { Location = new Point(120, 110), Size = new Size(200, 25) };
                cboSiteType.Items.AddRange(new object[] { "类型一", "类型二", "类型三", "类型四" });

                var lblSiteCarId = new CCWin.SkinControl.SkinLabel { Text = "所属车间:", Location = new Point(30, 150) };
                cboSiteCarId = new CCWin.SkinControl.SkinComboBox { Location = new Point(120, 150), Size = new Size(200, 25) };

                var lblSiteLineId = new CCWin.SkinControl.SkinLabel { Text = "所属生产线:", Location = new Point(30, 190) };
                cboSiteLineId = new CCWin.SkinControl.SkinComboBox { Location = new Point(120, 190), Size = new Size(200, 25) };

                var lblSiteProcessId = new CCWin.SkinControl.SkinLabel { Text = "工序:", Location = new Point(30, 230) };
                cboSiteProcessId = new CCWin.SkinControl.SkinComboBox { Location = new Point(120, 230), Size = new Size(200, 25) };
                cboSiteProcessId.Items.AddRange(new object[] { "工序一", "工序二", "工序三", "工序四" });

                                 var lblSiteLocal = new CCWin.SkinControl.SkinLabel { Text = "位置:", Location = new Point(30, 270) };
                 cboSiteLocal = new CCWin.SkinControl.SkinComboBox { Location = new Point(120, 270), Size = new Size(200, 25) };
                 cboSiteLocal.Items.AddRange(new object[] { "开始站点", "标准站点", "下线站点", "独立站点" });

                btnSiteSave = new CCWin.SkinControl.SkinButton
                {
                    Text = "保存",
                    Size = new Size(80, 35),
                    Location = new Point(120, 320)
                };
                btnSiteSave.Click += BtnSiteSave_Click;

                btnSiteClear = new CCWin.SkinControl.SkinButton
                {
                    Text = "清空",
                    Size = new Size(80, 35),
                    Location = new Point(220, 320)
                };
                btnSiteClear.Click += BtnSiteClear_Click;

                // 加载车间和生产线数据
                LoadSiteFormData();

                // 添加控件到表单
                siteAddForm.Controls.AddRange(new Control[]
                {
                    lblSiteCode, txtSiteCode,
                    lblSiteName, txtSiteName,
                    lblSiteType, cboSiteType,
                    lblSiteCarId, cboSiteCarId,
                    lblSiteLineId, cboSiteLineId,
                    lblSiteProcessId, cboSiteProcessId,
                    lblSiteLocal, cboSiteLocal,
                    btnSiteSave, btnSiteClear
                });

                siteAddForm.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建站点新增表单时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 加载站点表单数据
        /// </summary>
        private async void LoadSiteFormData()
        {
            try
            {
                // 加载车间数据到下拉框
                var carResponse = await ApiRequestHelper.GetAsync<ApiCarInfoResponse>("api/Car/GetCar");
                if (carResponse.Success && carResponse.Data?.code == 200 && carResponse.Data.data != null)
                {
                    cboSiteCarId.Items.Clear();
                    foreach (var car in carResponse.Data.data)
                    {
                        cboSiteCarId.Items.Add($"{car.CarName} ({car.CarCode})");
                    }
                }

                // 加载生产线数据到下拉框
                var lineResponse = await ApiRequestHelper.GetAsync<ApiProductLineInfoResponse>("api/Car/GetProductLine");
                if (lineResponse.Success && lineResponse.Data?.code == 200 && lineResponse.Data.data != null)
                {
                    cboSiteLineId.Items.Clear();
                    foreach (var line in lineResponse.Data.data)
                    {
                        cboSiteLineId.Items.Add($"{line.LineName} ({line.LineCode})");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载站点表单数据时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 站点保存按钮点击事件
        /// </summary>
        private async void BtnSiteSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (ValidateSiteInput())
                {
                    var siteData = BuildSiteData();
                    bool success = await AddSiteAsync(siteData);
                    if (success)
                    {
                        MessageBox.Show("站点添加成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        LoadSiteData();
                        ((Form)((Button)sender).Parent).Close();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存站点时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 站点清空按钮点击事件
        /// </summary>
        private void BtnSiteClear_Click(object sender, EventArgs e)
        {
            txtSiteCode.Text = "";
            txtSiteName.Text = "";
            cboSiteType.SelectedIndex = -1;
            cboSiteCarId.SelectedIndex = -1;
            cboSiteLineId.SelectedIndex = -1;
            cboSiteProcessId.SelectedIndex = -1;
            cboSiteLocal.SelectedIndex = -1;
        }

        /// <summary>
        /// 验证站点输入数据
        /// </summary>
        private bool ValidateSiteInput()
        {
            if (string.IsNullOrWhiteSpace(txtSiteCode.Text))
            {
                MessageBox.Show("请输入站点编号", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtSiteCode.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txtSiteName.Text))
            {
                MessageBox.Show("请输入站点名称", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtSiteName.Focus();
                return false;
            }

            return true;
        }

        /// <summary>
        /// 构建站点数据
        /// </summary>
        private SitaAddData BuildSiteData()
        {
            return new SitaAddData
            {
                SiteCode = txtSiteCode.Text.Trim(),
                SiteName = txtSiteName.Text.Trim(),
                SiteType = GetSiteTypeValue(cboSiteType.Text),
                CarId = cboSiteCarId.SelectedIndex + 1,
                LineId = cboSiteLineId.SelectedIndex + 1,
                ProcessId = cboSiteProcessId.SelectedIndex + 1,
                SiteLocal = cboSiteLocal.Text
            };
        }

        /// <summary>
        /// 获取站点类型值
        /// </summary>
        private int GetSiteTypeValue(string siteTypeText)
        {
            switch (siteTypeText)
            {
                case "类型一": return 1;
                case "类型二": return 2;
                case "类型三": return 3;
                case "类型四": return 4;
                default: return 1;
            }
        }

        /// <summary>
        /// 调用API添加站点
        /// </summary>
        private async Task<bool> AddSiteAsync(SitaAddData siteData)
        {
            try
            {
                var requestData = new
                {
                    siteCode = siteData.SiteCode,
                    siteName = siteData.SiteName,
                    siteType = siteData.SiteType,
                    carId = siteData.CarId,
                    lineId = siteData.LineId,
                    processId = siteData.ProcessId,
                    siteLocal = siteData.SiteLocal
                };

                var apiResponse = await ApiRequestHelper.PostAsync<ApiAddSiteResponse>("api/Car/Addsite", requestData);

                if (apiResponse.Success && apiResponse.Data?.code == 200)
                {
                    return true;
                }
                else
                {
                    ApiRequestHelper.ShowError($"站点添加失败: {apiResponse.Message}");
                    return false;
                }
            }
            catch (Exception ex)
            {
                ApiRequestHelper.ShowError($"添加站点时出错: {ex.Message}");
                return false;
            }
        }

        #endregion

        #region 新增站点功能

        /// <summary>
        /// 初始化新增站点页面
        /// </summary>
        private void InitializeSiteAddPage()
        {
            try
            {
                // 初始化新增站点页面
                InitializeSiteAddForm();
                
                Console.WriteLine("新增站点页面初始化完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化新增站点页面时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 初始化新增站点表单
        /// </summary>
        private void InitializeSiteAddForm()
        {
            try
            {
                if (tabSiteAdd == null)
                {
                    MessageBox.Show("新增站点页面未找到", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 创建标题标签
                var lblSiteAddTitle = new CCWin.SkinControl.SkinLabel
                {
                    Text = "新增站点",
                    Font = new Font("微软雅黑", 16F, FontStyle.Bold),
                    Location = new Point(30, 30),
                    Size = new Size(200, 40),
                    BackColor = Color.Transparent
                };

                // 创建表单控件
                var lblSiteCode = new CCWin.SkinControl.SkinLabel { Text = "站点编号:", Location = new Point(50, 100), Size = new Size(100, 25) };
                var txtSiteCode = new CCWin.SkinControl.SkinTextBox { Location = new Point(160, 100), Size = new Size(200, 25) };

                var lblSiteName = new CCWin.SkinControl.SkinLabel { Text = "站点名称:", Location = new Point(50, 140), Size = new Size(100, 25) };
                var txtSiteName = new CCWin.SkinControl.SkinTextBox { Location = new Point(160, 140), Size = new Size(200, 25) };

                var lblSiteType = new CCWin.SkinControl.SkinLabel { Text = "站点类型:", Location = new Point(50, 180), Size = new Size(100, 25) };
                var cboSiteType = new CCWin.SkinControl.SkinComboBox { Location = new Point(160, 180), Size = new Size(200, 25) };
                cboSiteType.Items.AddRange(new object[] { "类型一", "类型二", "类型三", "类型四" });

                var lblSiteCarId = new CCWin.SkinControl.SkinLabel { Text = "所属车间:", Location = new Point(50, 220), Size = new Size(100, 25) };
                var cboSiteCarId = new CCWin.SkinControl.SkinComboBox { Location = new Point(160, 220), Size = new Size(200, 25) };

                var lblSiteLineId = new CCWin.SkinControl.SkinLabel { Text = "所属生产线:", Location = new Point(50, 260), Size = new Size(100, 25) };
                var cboSiteLineId = new CCWin.SkinControl.SkinComboBox { Location = new Point(160, 260), Size = new Size(200, 25) };

                var lblSiteProcessId = new CCWin.SkinControl.SkinLabel { Text = "工序:", Location = new Point(50, 300), Size = new Size(100, 25) };
                var cboSiteProcessId = new CCWin.SkinControl.SkinComboBox { Location = new Point(160, 300), Size = new Size(200, 25) };
                cboSiteProcessId.Items.AddRange(new object[] { "工序一", "工序二", "工序三", "工序四" });

                                 var lblSiteLocal = new CCWin.SkinControl.SkinLabel { Text = "位置:", Location = new Point(50, 340), Size = new Size(100, 25) };
                 var cboSiteLocal = new CCWin.SkinControl.SkinComboBox { Location = new Point(160, 340), Size = new Size(200, 25) };
                 cboSiteLocal.Items.AddRange(new object[] { "开始站点", "标准站点", "下线站点", "独立站点" });

                var btnSiteSave = new CCWin.SkinControl.SkinButton
                {
                    Text = "保存",
                    Size = new Size(100, 35),
                    Location = new Point(160, 400),
                    BackColor = Color.LightGreen
                };
                btnSiteSave.Click += BtnSiteAddSave_Click;

                var btnSiteClear = new CCWin.SkinControl.SkinButton
                {
                    Text = "清空",
                    Size = new Size(100, 35),
                    Location = new Point(280, 400),
                    BackColor = Color.LightYellow
                };
                btnSiteClear.Click += BtnSiteAddClear_Click;

                // 加载车间和生产线数据
                LoadSiteAddFormData(cboSiteCarId, cboSiteLineId);

                // 添加控件到页面
                tabSiteAdd.Controls.AddRange(new Control[]
                {
                    lblSiteAddTitle,
                    lblSiteCode, txtSiteCode,
                    lblSiteName, txtSiteName,
                    lblSiteType, cboSiteType,
                    lblSiteCarId, cboSiteCarId,
                    lblSiteLineId, cboSiteLineId,
                    lblSiteProcessId, cboSiteProcessId,
                    lblSiteLocal, cboSiteLocal,
                    btnSiteSave, btnSiteClear
                });

                // 保存控件引用
                this.txtSiteCode = txtSiteCode;
                this.txtSiteName = txtSiteName;
                this.cboSiteType = cboSiteType;
                this.cboSiteCarId = cboSiteCarId;
                this.cboSiteLineId = cboSiteLineId;
                this.cboSiteProcessId = cboSiteProcessId;
                this.cboSiteLocal = cboSiteLocal;
                this.btnSiteSave = btnSiteSave;
                this.btnSiteClear = btnSiteClear;

                Console.WriteLine("新增站点表单初始化完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"初始化新增站点表单时出错: {ex.Message}");
                MessageBox.Show($"初始化新增站点表单时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 加载新增站点表单数据
        /// </summary>
        private async void LoadSiteAddFormData(CCWin.SkinControl.SkinComboBox cboSiteCarId, CCWin.SkinControl.SkinComboBox cboSiteLineId)
        {
            try
            {
                // 加载车间数据到下拉框
                var carResponse = await ApiRequestHelper.GetAsync<ApiCarInfoResponse>("api/Car/GetCar");
                if (carResponse.Success && carResponse.Data?.code == 200 && carResponse.Data.data != null)
                {
                    cboSiteCarId.Items.Clear();
                    foreach (var car in carResponse.Data.data)
                    {
                        cboSiteCarId.Items.Add($"{car.CarName} ({car.CarCode})");
                    }
                }

                // 加载生产线数据到下拉框
                var lineResponse = await ApiRequestHelper.GetAsync<ApiProductLineInfoResponse>("api/Car/GetProductLine");
                if (lineResponse.Success && lineResponse.Data?.code == 200 && lineResponse.Data.data != null)
                {
                    cboSiteLineId.Items.Clear();
                    foreach (var line in lineResponse.Data.data)
                    {
                        cboSiteLineId.Items.Add($"{line.LineName} ({line.LineCode})");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载新增站点表单数据时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 新增站点保存按钮点击事件
        /// </summary>
        private async void BtnSiteAddSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (ValidateSiteAddInput())
                {
                    var siteData = BuildSiteAddData();
                    bool success = await AddSiteAsync(siteData);
                    if (success)
                    {
                        MessageBox.Show("站点添加成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        ClearSiteAddForm();
                        // 刷新站点管理列表
                        LoadSiteData();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存站点时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 新增站点清空按钮点击事件
        /// </summary>
        private void BtnSiteAddClear_Click(object sender, EventArgs e)
        {
            ClearSiteAddForm();
        }

        /// <summary>
        /// 验证新增站点输入数据
        /// </summary>
        private bool ValidateSiteAddInput()
        {
            if (string.IsNullOrWhiteSpace(txtSiteCode.Text))
            {
                MessageBox.Show("请输入站点编号", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtSiteCode.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txtSiteName.Text))
            {
                MessageBox.Show("请输入站点名称", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtSiteName.Focus();
                return false;
            }

            if (cboSiteType.SelectedIndex == -1)
            {
                MessageBox.Show("请选择站点类型", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cboSiteType.Focus();
                return false;
            }

            if (cboSiteCarId.SelectedIndex == -1)
            {
                MessageBox.Show("请选择所属车间", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cboSiteCarId.Focus();
                return false;
            }

            if (cboSiteLineId.SelectedIndex == -1)
            {
                MessageBox.Show("请选择所属生产线", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cboSiteLineId.Focus();
                return false;
            }

            if (cboSiteProcessId.SelectedIndex == -1)
            {
                MessageBox.Show("请选择工序", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cboSiteProcessId.Focus();
                return false;
            }

            if (cboSiteLocal.SelectedIndex == -1)
            {
                MessageBox.Show("请选择位置", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cboSiteLocal.Focus();
                return false;
            }

            return true;
        }

        /// <summary>
        /// 构建新增站点数据
        /// </summary>
        private SitaAddData BuildSiteAddData()
        {
            return new SitaAddData
            {
                SiteCode = txtSiteCode.Text.Trim(),
                SiteName = txtSiteName.Text.Trim(),
                SiteType = GetSiteTypeValue(cboSiteType.Text),
                CarId = cboSiteCarId.SelectedIndex + 1,
                LineId = cboSiteLineId.SelectedIndex + 1,
                ProcessId = cboSiteProcessId.SelectedIndex + 1,
                SiteLocal = cboSiteLocal.Text
            };
        }

        /// <summary>
        /// 清空新增站点表单
        /// </summary>
        private void ClearSiteAddForm()
        {
            txtSiteCode.Text = "";
            txtSiteName.Text = "";
            cboSiteType.SelectedIndex = -1;
            cboSiteCarId.SelectedIndex = -1;
            cboSiteLineId.SelectedIndex = -1;
            cboSiteProcessId.SelectedIndex = -1;
            cboSiteLocal.SelectedIndex = -1;
            txtSiteCode.Focus();
        }

        #endregion

        #region 新增生产线功能

        /// <summary>
        /// 初始化新增生产线页面
        /// </summary>
        private void InitializeProductLineAddPage()
        {
            try
            {
                // 初始化新增生产线页面
                InitializeProductLineAddForm();
                
                Console.WriteLine("新增生产线页面初始化完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化新增生产线页面时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 初始化新增生产线表单
        /// </summary>
        private void InitializeProductLineAddForm()
        {
            try
            {
                if (tabProductLineAdd == null)
                {
                    MessageBox.Show("新增生产线页面未找到", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 创建标题标签
                var lblProductLineAddTitle = new CCWin.SkinControl.SkinLabel
                {
                    Text = "新增生产线",
                    Font = new Font("微软雅黑", 16F, FontStyle.Bold),
                    Location = new Point(30, 30),
                    Size = new Size(200, 40),
                    BackColor = Color.Transparent
                };

                // 创建表单控件
                var lblLineCode = new CCWin.SkinControl.SkinLabel { Text = "生产线编号:", Location = new Point(50, 100), Size = new Size(100, 25) };
                var txtLineCode = new CCWin.SkinControl.SkinTextBox { Location = new Point(160, 100), Size = new Size(200, 25) };

                var lblLineName = new CCWin.SkinControl.SkinLabel { Text = "生产线名称:", Location = new Point(50, 140), Size = new Size(100, 25) };
                var txtLineName = new CCWin.SkinControl.SkinTextBox { Location = new Point(160, 140), Size = new Size(200, 25) };

                var lblLineType = new CCWin.SkinControl.SkinLabel { Text = "生产线类型:", Location = new Point(50, 180), Size = new Size(100, 25) };
                var cboLineType = new CCWin.SkinControl.SkinComboBox { Location = new Point(160, 180), Size = new Size(200, 25) };
                cboLineType.Items.AddRange(new object[] { "类型一", "类型二", "类型三", "类型四" });

                var lblLineCarId = new CCWin.SkinControl.SkinLabel { Text = "所属车间:", Location = new Point(50, 220), Size = new Size(100, 25) };
                var cboLineCarId = new CCWin.SkinControl.SkinComboBox { Location = new Point(160, 220), Size = new Size(200, 25) };

                var btnLineSave = new CCWin.SkinControl.SkinButton
                {
                    Text = "保存",
                    Size = new Size(100, 35),
                    Location = new Point(160, 280),
                    BackColor = Color.LightGreen
                };
                btnLineSave.Click += BtnProductLineAddSave_Click;

                var btnLineClear = new CCWin.SkinControl.SkinButton
                {
                    Text = "清空",
                    Size = new Size(100, 35),
                    Location = new Point(280, 280),
                    BackColor = Color.LightYellow
                };
                btnLineClear.Click += BtnProductLineAddClear_Click;

                // 加载车间数据
                LoadProductLineAddFormData(cboLineCarId);

                // 添加控件到页面
                tabProductLineAdd.Controls.AddRange(new Control[]
                {
                    lblProductLineAddTitle,
                    lblLineCode, txtLineCode,
                    lblLineName, txtLineName,
                    lblLineType, cboLineType,
                    lblLineCarId, cboLineCarId,
                    btnLineSave, btnLineClear
                });

                // 保存控件引用
                this.txtLineCode = txtLineCode;
                this.txtLineName = txtLineName;
                this.cboLineType = cboLineType;
                this.cboLineCarId = cboLineCarId;
                this.btnLineSave = btnLineSave;
                this.btnLineClear = btnLineClear;

                Console.WriteLine("新增生产线表单初始化完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"初始化新增生产线表单时出错: {ex.Message}");
                MessageBox.Show($"初始化新增生产线表单时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 加载新增生产线表单数据
        /// </summary>
        private async void LoadProductLineAddFormData(CCWin.SkinControl.SkinComboBox cboLineCarId)
        {
            try
            {
                // 加载车间数据到下拉框
                var carResponse = await ApiRequestHelper.GetAsync<ApiCarInfoResponse>("api/Car/GetCar");
                if (carResponse.Success && carResponse.Data?.code == 200 && carResponse.Data.data != null)
                {
                    cboLineCarId.Items.Clear();
                    foreach (var car in carResponse.Data.data)
                    {
                        cboLineCarId.Items.Add($"{car.CarName} ({car.CarCode})");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载新增生产线表单数据时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 新增生产线保存按钮点击事件
        /// </summary>
        private async void BtnProductLineAddSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (ValidateProductLineAddInput())
                {
                    var productLineData = BuildProductLineAddData();
                    bool success = await AddProductLineAddAsync(productLineData);
                    if (success)
                    {
                        MessageBox.Show("生产线添加成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        ClearProductLineAddForm();
                        // 刷新生产线管理列表
                        LoadProductLineData();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存生产线时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 新增生产线清空按钮点击事件
        /// </summary>
        private void BtnProductLineAddClear_Click(object sender, EventArgs e)
        {
            ClearProductLineAddForm();
        }

        /// <summary>
        /// 验证新增生产线输入数据
        /// </summary>
        private bool ValidateProductLineAddInput()
        {
            if (string.IsNullOrWhiteSpace(txtLineCode.Text))
            {
                MessageBox.Show("请输入生产线编号", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtLineCode.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txtLineName.Text))
            {
                MessageBox.Show("请输入生产线名称", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtLineName.Focus();
                return false;
            }

            if (cboLineType.SelectedIndex == -1)
            {
                MessageBox.Show("请选择生产线类型", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cboLineType.Focus();
                return false;
            }

            if (cboLineCarId.SelectedIndex == -1)
            {
                MessageBox.Show("请选择所属车间", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cboLineCarId.Focus();
                return false;
            }

            return true;
        }

        /// <summary>
        /// 构建新增生产线数据
        /// </summary>
        private ProductLineData BuildProductLineAddData()
        {
            return new ProductLineData
            {
                LineCode = txtLineCode.Text.Trim(),
                LineName = txtLineName.Text.Trim(),
                LineType = GetLineTypeValue(cboLineType.Text),
                CarId = cboLineCarId.SelectedIndex + 1
            };
        }

        /// <summary>
        /// 清空新增生产线表单
        /// </summary>
        private void ClearProductLineAddForm()
        {
            txtLineCode.Text = "";
            txtLineName.Text = "";
            cboLineType.SelectedIndex = -1;
            cboLineCarId.SelectedIndex = -1;
            txtLineCode.Focus();
        }

        /// <summary>
        /// 调用API添加生产线（新增页面专用）
        /// </summary>
        private async Task<bool> AddProductLineAddAsync(ProductLineData productLineData)
        {
            try
            {
                var requestData = new
                {
                    lineCode = productLineData.LineCode,
                    lineName = productLineData.LineName,
                    lineType = productLineData.LineType,
                    carId = productLineData.CarId
                };

                var apiResponse = await ApiRequestHelper.PostAsync<ApiProductLineResponse>("api/Car/AddProductLine", requestData);

                if (apiResponse.Success && apiResponse.Data?.code == 200)
                {
                    return true;
                }
                else
                {
                    ApiRequestHelper.ShowError($"生产线添加失败: {apiResponse.Message}");
                    return false;
                }
            }
            catch (Exception ex)
            {
                ApiRequestHelper.ShowError($"添加生产线时出错: {ex.Message}");
                return false;
            }
        }

        #endregion

        #region 生产线管理功能

        /// <summary>
        /// 初始化生产线管理
        /// </summary>
        private void InitializeProductLineManagement()
        {
            try
            {
                InitializeProductLineManagePage();
                Console.WriteLine("生产线管理初始化完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化生产线管理时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 初始化生产线管理页面
        /// </summary>
        private void InitializeProductLineManagePage()
        {
            try
            {
                if (tabProductLineManage == null)
                {
                    MessageBox.Show("生产线管理页面未找到", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 创建生产线管理DataGridView
                dgvProductLines = new CCWin.SkinControl.SkinDataGridView();
                dgvProductLines.Name = "dgvProductLines";
                dgvProductLines.Dock = DockStyle.Fill;
                dgvProductLines.Location = new Point(0, 0);
                dgvProductLines.Size = new Size(tabProductLineManage.Width, tabProductLineManage.Height - 60);

                // 设置DataGridView属性
                dgvProductLines.AutoGenerateColumns = false;
                dgvProductLines.AllowUserToAddRows = false;
                dgvProductLines.AllowUserToDeleteRows = false;
                dgvProductLines.ReadOnly = true;
                dgvProductLines.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                dgvProductLines.MultiSelect = false;
                dgvProductLines.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

                // 添加列定义
                dgvProductLines.Columns.Add(new DataGridViewTextBoxColumn
                {
                    HeaderText = "生产线编号",
                    DataPropertyName = "LineCode",
                    Width = 100
                });

                dgvProductLines.Columns.Add(new DataGridViewTextBoxColumn
                {
                    HeaderText = "生产线名称",
                    DataPropertyName = "LineName",
                    Width = 120
                });

                // 添加生产线类型列（自定义显示）
                var lineTypeColumn = new DataGridViewTextBoxColumn
                {
                    HeaderText = "生产线类型",
                    Name = "LineTypeColumn",
                    Width = 100
                };
                dgvProductLines.Columns.Add(lineTypeColumn);

                // 添加所属车间列（直接绑定CarName字段）
                dgvProductLines.Columns.Add(new DataGridViewTextBoxColumn
                {
                    HeaderText = "所属车间",
                    DataPropertyName = "CarName",
                    Width = 100
                });

                // 设置样式
                dgvProductLines.BackgroundColor = Color.White;
                dgvProductLines.BorderStyle = BorderStyle.None;
                dgvProductLines.GridColor = Color.LightGray;
                dgvProductLines.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(240, 240, 240);
                dgvProductLines.ColumnHeadersDefaultCellStyle.Font = new Font("微软雅黑", 9F, FontStyle.Bold);
                dgvProductLines.DefaultCellStyle.Font = new Font("微软雅黑", 9F);
                dgvProductLines.RowHeadersVisible = false;
                
                // 绑定数据绑定完成事件
                dgvProductLines.DataBindingComplete += DgvProductLines_DataBindingComplete;

                // 创建按钮面板
                var buttonPanel = new Panel
                {
                    Dock = DockStyle.Bottom,
                    Height = 60,
                    BackColor = Color.White
                };

                // 创建按钮
                btnProductLineRefresh = new CCWin.SkinControl.SkinButton
                {
                    Text = "刷新",
                    Size = new Size(80, 35),
                    Location = new Point(20, 15)
                };
                btnProductLineRefresh.Click += BtnProductLineRefresh_Click;

                btnProductLineAdd = new CCWin.SkinControl.SkinButton
                {
                    Text = "新增生产线",
                    Size = new Size(100, 35),
                    Location = new Point(120, 15)
                };
                btnProductLineAdd.Click += BtnProductLineAdd_Click;

                // 添加控件到面板
                buttonPanel.Controls.Add(btnProductLineRefresh);
                buttonPanel.Controls.Add(btnProductLineAdd);

                // 添加控件到页面
                tabProductLineManage.Controls.Add(dgvProductLines);
                tabProductLineManage.Controls.Add(buttonPanel);

                Console.WriteLine("生产线管理页面初始化完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"初始化生产线管理页面时出错: {ex.Message}");
                MessageBox.Show($"初始化生产线管理页面时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 加载生产线数据
        /// </summary>
        private async void LoadProductLineData()
        {
            try
            {
                Console.WriteLine("=== 开始加载生产线数据 ===");

                if (dgvProductLines == null)
                {
                    MessageBox.Show("生产线DataGridView控件未找到", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                dgvProductLines.DataSource = null;

                Console.WriteLine("正在调用生产线信息API...");
                var apiResponse = await ApiRequestHelper.GetAsync<ApiProductLineInfoResponse>("api/Car/GetProductLine");

                if (apiResponse.Success && apiResponse.Data?.code == 200 && apiResponse.Data.data != null)
                {
                    Console.WriteLine($"生产线信息API调用成功，数据条数: {apiResponse.Data.data.Count}");

                    productLineList = apiResponse.Data.data;
                    dgvProductLines.DataSource = productLineList;

                    dgvProductLines.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);

                    Console.WriteLine($"成功加载 {productLineList.Count} 个生产线数据");
                    Console.WriteLine("=== 生产线数据加载完成 ===");
                }
                else
                {
                    Console.WriteLine($"生产线信息API调用失败: {apiResponse.Message}");
                    ApiRequestHelper.ShowError($"生产线数据加载失败: {apiResponse.Message}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载生产线数据时出错: {ex.Message}");
                MessageBox.Show($"加载生产线数据时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 生产线数据绑定完成事件
        /// </summary>
        private void DgvProductLines_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            try
            {
                // 手动填充生产线类型列
                for (int i = 0; i < dgvProductLines.Rows.Count; i++)
                {
                    if (i < productLineList.Count)
                    {
                        var line = productLineList[i];
                        var lineTypeText = GetLineTypeText(line.LineType);
                        
                        Console.WriteLine($"生产线 {line.LineCode}: LineType={line.LineType} -> {lineTypeText}");
                        
                        dgvProductLines.Rows[i].Cells["LineTypeColumn"].Value = lineTypeText;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"填充生产线自定义列时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 生产线刷新按钮点击事件
        /// </summary>
        private void BtnProductLineRefresh_Click(object sender, EventArgs e)
        {
            LoadProductLineData();
        }

        /// <summary>
        /// 生产线新增按钮点击事件
        /// </summary>
        private void BtnProductLineAdd_Click(object sender, EventArgs e)
        {
            ShowProductLineAddForm();
        }

        /// <summary>
        /// 显示生产线新增表单
        /// </summary>
        private void ShowProductLineAddForm()
        {
            try
            {
                // 创建生产线新增表单
                var productLineAddForm = new Form
                {
                    Text = "新增生产线",
                    Size = new Size(450, 350),
                    StartPosition = FormStartPosition.CenterParent,
                    FormBorderStyle = FormBorderStyle.FixedDialog,
                    MaximizeBox = false,
                    MinimizeBox = false
                };

                // 创建表单控件
                var lblLineCode = new CCWin.SkinControl.SkinLabel { Text = "生产线编号:", Location = new Point(30, 30) };
                txtLineCode = new CCWin.SkinControl.SkinTextBox { Location = new Point(120, 30), Size = new Size(200, 25) };

                var lblLineName = new CCWin.SkinControl.SkinLabel { Text = "生产线名称:", Location = new Point(30, 70) };
                txtLineName = new CCWin.SkinControl.SkinTextBox { Location = new Point(120, 70), Size = new Size(200, 25) };

                var lblLineType = new CCWin.SkinControl.SkinLabel { Text = "生产线类型:", Location = new Point(30, 110) };
                cboLineType = new CCWin.SkinControl.SkinComboBox { Location = new Point(120, 110), Size = new Size(200, 25) };
                cboLineType.Items.AddRange(new object[] { "类型一", "类型二", "类型三", "类型四" });

                var lblLineCarId = new CCWin.SkinControl.SkinLabel { Text = "所属车间:", Location = new Point(30, 150) };
                cboLineCarId = new CCWin.SkinControl.SkinComboBox { Location = new Point(120, 150), Size = new Size(200, 25) };

                btnLineSave = new CCWin.SkinControl.SkinButton
                {
                    Text = "保存",
                    Size = new Size(80, 35),
                    Location = new Point(120, 200)
                };
                btnLineSave.Click += BtnLineSave_Click;

                btnLineClear = new CCWin.SkinControl.SkinButton
                {
                    Text = "清空",
                    Size = new Size(80, 35),
                    Location = new Point(220, 200)
                };
                btnLineClear.Click += BtnLineClear_Click;

                // 加载车间数据
                LoadProductLineFormData();

                // 添加控件到表单
                productLineAddForm.Controls.AddRange(new Control[]
                {
                    lblLineCode, txtLineCode,
                    lblLineName, txtLineName,
                    lblLineType, cboLineType,
                    lblLineCarId, cboLineCarId,
                    btnLineSave, btnLineClear
                });

                productLineAddForm.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建生产线新增表单时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 加载生产线表单数据
        /// </summary>
        private async void LoadProductLineFormData()
        {
            try
            {
                // 加载车间数据到下拉框
                var carResponse = await ApiRequestHelper.GetAsync<ApiCarInfoResponse>("api/Car/GetCar");
                if (carResponse.Success && carResponse.Data?.code == 200 && carResponse.Data.data != null)
                {
                    cboLineCarId.Items.Clear();
                    foreach (var car in carResponse.Data.data)
                    {
                        cboLineCarId.Items.Add($"{car.CarName} ({car.CarCode})");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载生产线表单数据时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 生产线保存按钮点击事件
        /// </summary>
        private async void BtnLineSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (ValidateProductLineInput())
                {
                    var productLineData = BuildProductLineData();
                    bool success = await AddProductLineAsync(productLineData);
                    if (success)
                    {
                        MessageBox.Show("生产线添加成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        LoadProductLineData();
                        ((Form)((Button)sender).Parent).Close();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存生产线时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 生产线清空按钮点击事件
        /// </summary>
        private void BtnLineClear_Click(object sender, EventArgs e)
        {
            txtLineCode.Text = "";
            txtLineName.Text = "";
            cboLineType.SelectedIndex = -1;
            cboLineCarId.SelectedIndex = -1;
        }

        /// <summary>
        /// 验证生产线输入数据
        /// </summary>
        private bool ValidateProductLineInput()
        {
            if (string.IsNullOrWhiteSpace(txtLineCode.Text))
            {
                MessageBox.Show("请输入生产线编号", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtLineCode.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txtLineName.Text))
            {
                MessageBox.Show("请输入生产线名称", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtLineName.Focus();
                return false;
            }

            return true;
        }

        /// <summary>
        /// 构建生产线数据
        /// </summary>
        private ProductLineData BuildProductLineData()
        {
            return new ProductLineData
            {
                LineCode = txtLineCode.Text.Trim(),
                LineName = txtLineName.Text.Trim(),
                LineType = GetLineTypeValue(cboLineType.Text),
                CarId = cboLineCarId.SelectedIndex + 1
            };
        }

        /// <summary>
        /// 获取生产线类型值
        /// </summary>
        private int GetLineTypeValue(string lineTypeText)
        {
            switch (lineTypeText)
            {
                case "类型一": return 1;
                case "类型二": return 2;
                case "类型三": return 3;
                case "类型四": return 4;
                default: return 1;
            }
        }

        /// <summary>
        /// 获取工序文字
        /// </summary>
        private string GetProcessText(int processId)
        {
            switch (processId)
            {
                case 1: return "工序一";
                case 2: return "工序二";
                case 3: return "工序三";
                case 4: return "工序四";
                default: return $"工序{processId}";
            }
        }

        /// <summary>
        /// 获取站点类型文字
        /// </summary>
        private string GetSiteTypeText(int siteType)
        {
            switch (siteType)
            {
                case 1: return "类型一";
                case 2: return "类型二";
                case 3: return "类型三";
                case 4: return "类型四";
                default: return $"类型{siteType}";
            }
        }

        /// <summary>
        /// 获取生产线类型文字
        /// </summary>
        private string GetLineTypeText(int lineType)
        {
            switch (lineType)
            {
                case 1: return "类型一";
                case 2: return "类型二";
                case 3: return "类型三";
                case 4: return "类型四";
                default: return $"类型{lineType}";
            }
        }



        /// <summary>
        /// 调用API添加生产线
        /// </summary>
        private async Task<bool> AddProductLineAsync(ProductLineData productLineData)
        {
            try
            {
                var requestData = new
                {
                    lineCode = productLineData.LineCode,
                    lineName = productLineData.LineName,
                    lineType = productLineData.LineType,
                    carId = productLineData.CarId
                };

                var apiResponse = await ApiRequestHelper.PostAsync<ApiProductLineResponse>("api/ProductLine/AddProductLine", requestData);

                if (apiResponse.Success && apiResponse.Data?.code == 200)
                {
                    return true;
                }
                else
                {
                    ApiRequestHelper.ShowError($"生产线添加失败: {apiResponse.Message}");
                    return false;
                }
            }
            catch (Exception ex)
            {
                ApiRequestHelper.ShowError($"添加生产线时出错: {ex.Message}");
                return false;
            }
        }

        #endregion
    }
}
